package com.lovo.shirodemo.shiro;

import com.lovo.shirodemo.model.dto.FunctionInfoDTO;
import com.lovo.shirodemo.model.dto.RoleDTO;
import com.lovo.shirodemo.model.dto.UserInfoDTO;
import com.lovo.shirodemo.service.FunctionInfoService;
import com.lovo.shirodemo.service.UserInfoService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.List;

public class CustomRealm extends AuthorizingRealm {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private FunctionInfoService functionInfoService;

    /**
     * 权限分配
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取用户拥有的角色，以及角色拥有的权限
        UserInfoDTO userInfoDTO = (UserInfoDTO) principalCollection.getPrimaryPrincipal();
        //通过SimpleAuthenticationInfo做授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        List<RoleDTO> roleList = userInfoDTO.getRoleList();
        List<FunctionInfoDTO> functionInfoList = functionInfoService.findByRoleIds(roleList);
        // 把用户拥有的角色名称赋值给权限对象
        for(RoleDTO role : roleList){
            simpleAuthorizationInfo.addRole(role.getRoleName());
        }
        // 把角色对应的权限赋值给权限对象
        for(FunctionInfoDTO functionInfo : functionInfoList){
            simpleAuthorizationInfo.addStringPermission(functionInfo.getFunctionName());
        }

        return simpleAuthorizationInfo;
    }

    /**
     * 身份认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取用户输入的账号
        String phone = (String) authenticationToken.getPrincipal();
        //2.通过username从数据库中查找到user实体
        UserInfoDTO userInfoDTO = userInfoService.findByPhone(phone);
        if (userInfoDTO == null) {
            return null;
        }
        //3.通过SimpleAuthenticationInfo做身份处理
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userInfoDTO, userInfoDTO.getPwd(), userInfoDTO.getPhone());
        //4.返回身份处理对象
        return simpleAuthenticationInfo;

    }
}
